<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Divination;
use App\Models\YaoDivination;
use App\Models\PayConfig;
use App\Models\UserDivinationRecord;
use App\Models\AuspiciousWord;
use App\Models\DeviceRecord;
use App\Models\Draw;
use App\Models\Style;
use App\Models\DrawRecord;
use App\Models\PicRecord;
use App\Models\PicContentRecord;
use App\Models\JxRelation;
use App\Models\JxList;
use App\Models\SbcsRecord;
use App\Models\HanziRecord;
use App\Models\ZzxjRecord;
use Carbon\Carbon;
use DB;
use App\Http\Controllers\Api\V1\Requests\DivinationStoreRequest;
use App\Http\Controllers\Api\V1\Resources\UserDivinationRecordItemResource;
use App\Http\Controllers\Api\V1\Resources\DivinationCategoriesResource;
use App\Http\Controllers\Api\V1\Requests\DivinationStoreYzyRequest;
use App\Http\Controllers\Api\V1\Requests\DivinationZzxjRequest;
use App\Http\Controllers\Api\V1\Resources\UserDivinationRecordYzyItemResource;
use App\Http\Controllers\Api\V1\Resources\DrawRecordsResource;
use App\Http\Controllers\Api\V1\Resources\UserDivinationRecordPicItemResource;
use App\Http\Controllers\Api\V1\Resources\ChatRecordsResource;
use App\Http\Controllers\Api\V1\Resources\UserDivinationRecordZzxjItemResource;
use Overtrue\Pinyin\Pinyin;
use App\Http\Controllers\Api\V1\Resources\PicRecordsResource;
use Overtrue\ChineseCalendar\Calendar;
use App\Models\ScenicDivination;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Cache;

class DivinationController extends Controller
{
    
    
    public function storeyzy()
    {
        $upper_num = request('upper_num');
      $lower_num = request('lower_num');
      $yao_num = request('yao_num');
      $cause = request('cause');

      $request = app(DivinationStoreYzyRequest::class);
       
      $user = request()->user();
        
       $upper_num_remainder = intval($upper_num) % 8;
     $upper_num_remainder = $upper_num_remainder == 0 ? 8 : $upper_num_remainder;
     $lower_num_remainder = intval($lower_num) % 8;
     $lower_num_remainder =  $lower_num_remainder == 0 ? 8 : $lower_num_remainder;



     $divination = Divination::query()->where("upper_num",$upper_num_remainder)->where("lower_num",$lower_num_remainder)->first();

     if(!$divination){

        fail("出错了！！！");
     }

      $yao_num_remainder = intval($yao_num) % 6;
      $yao_num_remainder = $yao_num_remainder == 0 ? 6 : $yao_num_remainder;

      $byDivination = YaoDivination::where("yao_count",$yao_num_remainder)->where('divination_id',$divination->id)->first();
      if(!$byDivination){

        fail("出错了！！！");
     }
    

       $record =  $user->userDivinationRecord()->create([
            "upper_num" =>$upper_num,
            "lower_num"=> $lower_num,
            "yao_num"=>$yao_num,
            "cause"=>$cause,
            "divination_id"=>$divination->id,
            'by_dividend_id'=>$byDivination->by_dividend_id,
            'yao_dividend_id'=>$byDivination->id,
            'scenic_area_id' => 1,
       ]);

       $returnRes = [
          "record_id"=>$record->id,
          "title"=>$divination->title,
          "symbol"=> $divination->symbol,
          "content"=> $divination->content,
          "image"=> $divination->image
       ];
       return response()->json($returnRes);
        
       
       
    }


    public function storeDay()
    {

        $tgYear = request('tgYear');
        $tgMonth = request('tgMonth');
        $tgDay = request('tgDay');
        $dayLurNum = request('dayLurNum');
        $tgHour = request('tgHour');
        $type = request('type');


        $yearNum = config("site.xushu")[$tgYear];
        $monthNum = config("site.xushu")[$tgMonth];
        $dayNum = config("site.xushu")[$tgDay];
        $hourNum = config("site.xushu")[$tgHour];


        if($type==1){ //值日财神
          $upper_num = $yearNum + $monthNum + $dayLurNum;
          $lower_num = $yearNum + $monthNum + $dayLurNum + $hourNum;
          $yao_num = $hourNum;
        }elseif($type==2){ //值月财神
          $upper_num = $yearNum + $monthNum;
          $lower_num = $yearNum + $dayLurNum;
          $yao_num = $hourNum;

        }else{ //值月财神
          $upper_num = $yearNum;
          $lower_num = $yearNum + $dayLurNum;
          $yao_num = $hourNum;

        }

        //$request = app(DivinationStoreYzyRequest::class);
       
        $user = request()->user();
        
        $upper_num_remainder = intval($upper_num) % 8;
        $upper_num_remainder = $upper_num_remainder == 0 ? 8 : $upper_num_remainder;
        $lower_num_remainder = intval($lower_num) % 8;
        $lower_num_remainder =  $lower_num_remainder == 0 ? 8 : $lower_num_remainder;



        $divination = Divination::query()->where("upper_num",$upper_num_remainder)->where("lower_num",$lower_num_remainder)->first();

        if(!$divination){

          fail("出错了！！！");
        }

        $yao_num_remainder = intval($yao_num) % 6;
        $yao_num_remainder = $yao_num_remainder == 0 ? 6 : $yao_num_remainder;

        $byDivination = YaoDivination::where("yao_count",$yao_num_remainder)->where('divination_id',$divination->id)->first();
        if(!$byDivination){

          fail("出错了！！！");
        }
      

        $record =  $user->userDivinationRecord()->create([
            "upper_num" =>$upper_num,
            "lower_num"=> $lower_num,
            "yao_num"=>$yao_num,
            "divination_id"=>$divination->id,
            'by_dividend_id'=>$byDivination->by_dividend_id,
            'yao_dividend_id'=>$byDivination->id,
            'scenic_area_id' => 1,
            'type'=>$type,
        ]);

         $returnRes = [
            "record_id"=>$record->id,
            "title"=>$divination->title,
            "symbol"=> $divination->symbol,
            "content"=> $divination->content,
            "image"=> $divination->image
         ];
         return response()->json($returnRes);
       
    }

    public function store()
    {
        $upper_num = request('upper_num');
	    $lower_num = request('lower_num');
	    $yao_num = request('yao_num');
	    $cause = request('cause');
	    $birthday = request('birthday');

	    $request = app(DivinationStoreRequest::class);
       
	    $user = request()->user();
        
       $upper_num_remainder = intval($upper_num) % 8;
	   $upper_num_remainder = $upper_num_remainder == 0 ? 8 : $upper_num_remainder;
	   $lower_num_remainder = intval($lower_num) % 8;
	   $lower_num_remainder =  $lower_num_remainder == 0 ? 8 : $lower_num_remainder;



	   $divination = Divination::query()->where("upper_num",$upper_num_remainder)->where("lower_num",$lower_num_remainder)->first();

	   if(!$divination){

	    	fail("出错了！！！");
	   }

      $yao_num_remainder = intval($yao_num) % 6;
      $yao_num_remainder = $yao_num_remainder == 0 ? 6 : $yao_num_remainder;

      $byDivination = YaoDivination::where("yao_count",$yao_num_remainder)->where('divination_id',$divination->id)->first();
      if(!$byDivination){

        fail("出错了！！！");
     }
    

       $record =  $user->userDivinationRecord()->create([
       	    "upper_num" =>$upper_num,
	        "lower_num"=> $lower_num,
	        "yao_num"=>$yao_num,
	        "cause"=>$cause,
	        "birthday"=>date("Y-m-d H:i:s",$birthday),
	        "divination_id"=>$divination->id,
          'by_dividend_id'=>$byDivination->by_dividend_id,
          'yao_dividend_id'=>$byDivination->id,
       ]);

       $returnRes = [
	       	"record_id"=>$record->id,
	        "title"=>$divination->title,
	    	  "symbol"=> $divination->symbol,
	    	  "content"=> $divination->content,
	      	"image"=> $divination->image
       ];
       return response()->json($returnRes);
        
       
       
    }

    public function recordyzy($id)
    {
      $record = UserDivinationRecord::find($id);
      return new  UserDivinationRecordYzyItemResource($record);
   }
    public function record($id)
    {
      $record = UserDivinationRecord::find($id);
      return new  UserDivinationRecordItemResource($record);
    }

    public function deep()
    {
      $id= request('record_id');
      $categoryId= request('category_id');
      $record = UserDivinationRecord::find($id);
      return new  UserDivinationRecordItemResource($record);
   }

   public function deepyzy()
    {
      $id= request('record_id');
      $categoryId= request('category_id');
      $record = UserDivinationRecord::find($id);
      return new  UserDivinationRecordYzyItemResource($record);
   }

   public function list()
    {
      $user = request()->user();
      $list = $user->userDivinationRecord()->orderByDesc("id")->paginate();

      return UserDivinationRecordItemResource::collection($list);
   }

   

   public function configs ()
    {

      return response()->json(PayConfig::query()->where("type",0)->get());
   }

   public function picConfigs ()
    {

      return response()->json(PayConfig::query()->where("type",1)->get());
   }

   public function updateRecordByTimes ()
    {

    	$user = request()->user();

    	$record_id = request('record_id');

    	$record = UserDivinationRecord::find($record_id);

    	$user->decrement("times");
    	$record->update(['is_show'=>true]);

    	 return response(null, 200);
   }

   public function updateRecordByVip ()
    {
    	$record_id = request('record_id');

    	$record = UserDivinationRecord::find($record_id);
    	$record->update(['is_show'=>true]);
      return response(null, 200);
   }

   public function getRecordCategories()
   {
      $user = request()->user();
      $record_id = request('record_id');
      $record = UserDivinationRecord::find($record_id);
     
      if($record->user_id != $user->id){

         fail("出错了！！！");
      }

      $categories = $record->divinationCategoriesRelations()->get();
      
      return DivinationCategoriesResource::collection($categories);

   }

    public function randomWords()
    {
      $deviceId = request('device_id');

      if(!$deviceId){

         fail("参数缺失！");
      }

      $record = DeviceRecord::query()->where("device_id",$deviceId)->whereDate("created_at",Carbon::today())->first();

      if($record){
        $word = $record->words;
      }else{
       /* $word = AuspiciousWord::inRandomOrder()->first();
        $word = $word->words;*/

        
       $calendar = new Calendar();
       $result = $calendar->solar(date("Y"), date("m"), date("d"), date("H")); // 阳历，带 $hour 参数

       $ganZhiYear = $result['ganzhi_year'];

       $ganZhiMonth = $result['ganzhi_month'];
       $dayLurNum = $result['lunar_day'];
       $ganZhiHour = $result['ganzhi_hour'];

        $tgYear = mb_substr($ganZhiYear, -1, 1, 'UTF-8');  
        $tgMonth = mb_substr($ganZhiMonth, -1, 1, 'UTF-8'); 
        $tgHour = mb_substr($ganZhiHour, -1, 1, 'UTF-8'); 

        $yearNum = config("site.xushu")[$tgYear];
        $monthNum = config("site.xushu")[$tgMonth];
        $hourNum = config("site.xushu")[$tgHour];
      
        $upper_num = $yearNum + $monthNum + $dayLurNum;
        $lower_num = $yearNum + $monthNum + $dayLurNum + $hourNum;
        $yao_num = $hourNum;

         $upper_num_remainder = intval($upper_num) % 8;
        $upper_num_remainder = $upper_num_remainder == 0 ? 8 : $upper_num_remainder;
        $lower_num_remainder = intval($lower_num) % 8;
        $lower_num_remainder =  $lower_num_remainder == 0 ? 8 : $lower_num_remainder;



        $divination = Divination::query()->where("upper_num",$upper_num_remainder)->where("lower_num",$lower_num_remainder)->first();

        if(!$divination){

          fail("出错了！！！");
        }

        $yao_num_remainder = intval($yao_num) % 6;
        $yao_num_remainder = $yao_num_remainder == 0 ? 6 : $yao_num_remainder;

        $byDivination = YaoDivination::where("yao_count",$yao_num_remainder)->where('divination_id',$divination->id)->first();
        if(!$byDivination){

          fail("出错了！！！");
        }

         $scenicDivination = ScenicDivination::query()->where('divination_id',$divination->id)->where('scenic_area_id',1)->first();

         /*$word = "Hi，我来喽，您今天的财运要点如下，根据今天的天干地支五行来看，您今天的值日财神是 {$scenicDivination->uname}，您今日的生财方位是（{$scenicDivination->direction}），您今天适合关注的生财行业是（{$scenicDivination->hangye}），建议您今天采用的开运穿搭风格和配饰是（{$scenicDivination->dressing}）等等，另外，今天请一定要注意，（{$scenicDivination->precautions}）。好啦，希望能帮到您日进斗金，招财进宝！还有什么想了解的可以随时招呼我";*/

         $word = "又是美好的一天啊，让本财神帮您看看今天的财运情况哈,嘿，您今天的值日财神是 {$scenicDivination->uname}，您今天的生财方位是 {$scenicDivination->direction}，您今天适合涉及的财运行业包括{$scenicDivination->hangye}，您今天的开运穿搭可以考虑 {$scenicDivination->dressing}，哦对了，您今天还得注意{$scenicDivination->precautions}，希望您今天财运亨通，心情愉快呀！";

         DeviceRecord::create(["device_id"=>$deviceId,'words'=>$word]);
      }

     
      return response()->json(["word"=>$word]);
    }

    public function drawToZD()
    {
      $user = request()->user();
      $record = DrawRecord::query()->where("user_id",$user->id)->whereDate("created_at",Carbon::today())->orderByDesc("id")->first();

      $count = $user->drawRecords()->whereDate("created_at",Carbon::today())->count();


      if($count > 2){
        $response= [
           'word'=>$record->words,
           'image'=>img_path($record->draw->image),
           'name'=>$record->name ? $record->name :  $record->draw->name,
           'tag'=>$record->tag,
           'reason'=>$record->reason
        ]; 

      }else{
        $calendar = new Calendar();
        $result = $calendar->solar(date("Y"), date("m"), date("d"), date("H")); // 阳历，带 $hour 参数
        
        //获取月令五行
        $wuxingMonth = mb_substr($result['wuxing_month'], 1, 1);
        //获取日主五行
        $wuxingDay = mb_substr($result['wuxing_day'], 0, 1);
        
        $skgx = config("site.skgx")[$wuxingDay][$wuxingMonth];

        $sklb = array_column(config("site.sklb"),'name','sk');

        //月令和日主的生克关系
        $status  =$sklb[$skgx];

        $jxList = JxList::query()->where("is_better",true)->get()->pluck('id')->toArray();

        $betterSk = JxRelation::query()->whereIn("jx_list_id",$jxList)->where("status",$skgx)->get()->pluck('sk')->toArray();

        $betterSkWxAll = config("site.skgx")[$wuxingDay];

        $betterSkWxArr = [];
        $betterAttrs = [];
        $attrs = config("site.attrs");
        foreach($betterSkWxAll as $k=>$v){
            if(in_array($v,$betterSk)){
              $betterSkWxArr[] = $k;

              foreach($attrs as $ak=>$av){
                if($av == $k){
                  $betterAttrs[] = $ak;
                }
              }
            }

        }

        $betterSkWxStr = implode(",",$betterSkWxArr);

        /*$word = AuspiciousWord::inRandomOrder()->first();
        $word = $word->words;*/
        $draw = Draw::inRandomOrder()->whereIn('attr',$betterAttrs)->first();
        
        $attr =config("site.attrs")[$draw->attr];
        //日主和当前抽到卡牌的生克关系
        $sk = config("site.skgx")[$wuxingDay][$attr];

        $jxRelation = JxRelation::query()->where("sk",$sk)->where("status",$skgx)->first();
        
        $tag = "";
        if(isset($jxRelation->jx_list_id)){

          $jxRes = JxList::find($jxRelation->jx_list_id);

          $tag = $jxRes->name;
        }

        $word = $jxRelation->words;
        $name = $draw->name ."（".$attr."）";


        $reason = "今日主".$wuxingDay.",月令为".$wuxingMonth.",益（{$betterSkWxStr}）";

        $response= [
           'word'=> $word,
           'image'=> img_path($draw->image),
           'name'=> $name,
           'tag' => $tag,
           'reason' => $reason
        ]; 

        DrawRecord::create(["user_id"=>$user->id,'words'=>$word,'draw_id'=>$draw->id,'tag'=>$tag,'name'=>$name,'reason'=>$reason]);
      }

     
      return response()->json($response);
    }

    public function draw()
    {
      $user = request()->user();
      $record = DrawRecord::query()->where("user_id",$user->id)->whereDate("created_at",Carbon::today())->orderByDesc("id")->first();

      //$count = $user->drawRecords()->whereDate("created_at",Carbon::today())->count();


      if($record){
        $response= [
           'word'=>$record->words,
           'image'=>img_path($record->draw->image),
           'name'=>$record->name ? $record->name :  $record->draw->name,
           'tag'=>$record->tag,
           'reason'=>$record->reason
        ]; 

      }else{

        $calendar = new Calendar();
        $result = $calendar->solar(date("Y"), date("m"), date("d"), date("H")); // 阳历，带 $hour 参数
        
        //获取月令五行
        $wuxingMonth = mb_substr($result['wuxing_month'], 1, 1);
        //获取日主五行
        $wuxingDay = mb_substr($result['wuxing_day'], 0, 1);
        
        $skgx = config("site.skgx")[$wuxingDay][$wuxingMonth];

        $sklb = array_column(config("site.sklb"),'name','sk');

        //月令和日主的生克关系
        $status  =$sklb[$skgx];

        $jxList = JxList::query()->where("is_better",true)->get()->pluck('id')->toArray();

        $betterSk = JxRelation::query()->whereIn("jx_list_id",$jxList)->where("status",$skgx)->get()->pluck('sk')->toArray();

        $betterSkWxAll = config("site.skgx")[$wuxingDay];

        $betterSkWxArr = [];
        foreach($betterSkWxAll as $k=>$v){
            if(in_array($v,$betterSk)){
              $betterSkWxArr[] = $k;
            }

        }

        $betterSkWxStr = implode(",",$betterSkWxArr);
        


        /*$word = AuspiciousWord::inRandomOrder()->first();
        $word = $word->words;*/
        $draw = Draw::inRandomOrder()->first();
        
        $attr =config("site.attrs")[$draw->attr];
        //日主和当前抽到卡牌的生克关系
        $sk = config("site.skgx")[$wuxingDay][$attr];

        $jxRelation = JxRelation::query()->where("sk",$sk)->where("status",$skgx)->first();
        
        $tag = "";
        if(isset($jxRelation->jx_list_id)){

          $jxRes = JxList::find($jxRelation->jx_list_id);

          $tag = $jxRes->name;
        }

        $word = $jxRelation->words;
        $name = $draw->name ."（".$attr."）";


        $reason = "今日主".$wuxingDay.",月令为".$wuxingMonth.",益（{$betterSkWxStr}）";

        $response= [
           'word'=> $word,
           'image'=> img_path($draw->image),
           'name'=> $name,
           'tag' => $tag,
           'reason' => $reason
        ]; 
        
        DrawRecord::create(["user_id"=>$user->id,'words'=>$word,'draw_id'=>$draw->id,'tag'=>$tag,'name'=>$name,'reason'=>$reason]);
      }

     
      return response()->json($response);
    }

    public function drawlist()
   {
      $user = request()->user();
      $list = $user->drawRecords()->orderByDesc("id")->paginate();

      return DrawRecordsResource::collection($list);
   }

   public function piclist()
   {
      $user = request()->user();
      $list = $user->picRecords()->orderByDesc("id")->paginate();

      return PicRecordsResource::collection($list);
   }

   public function stylelist()
   {
      $user = request()->user();
      $list = Style::query()->orderByDesc("id")->get();

      return StylesResource::collection($list);
   }

    function extractJson($string) {
      preg_match('/\{(?:[^{}]|(?R))*\}/', $string, $matches);
      return $matches[0] ?? null;
    }

    public function pic()
    {

      $user = request()->user();
      $firstImage = request('firstImgSrc');
      $secondImgSrc = request('secondImgSrc');
      $type = request('type');


      if(!$firstImage || !$type){

         fail("参数缺失！");
      }
      if($type==2 && !$secondImgSrc){
         fail("请上传合图图片！");
      }

      if($type ==1 && $user->pic_times < 1){
         fail("解析次数不足~");
      }

      if($type ==2 && $user->pic_merge_times < 1){
         fail("解析次数不足~");
      }


      $model="gpt-4-turbo";

      if($type==2){

         $hasPrompt = Style::query()->where('id',1)->orderByDesc("id")->first();
      }else{

         $hasPrompt = Style::query()->where('id',2)->orderByDesc("id")->first();
      }
     
      $list = Style::query()->orderByDesc("id")->get();


       $messages = [];
      if($hasPrompt){
         //array_push($messages, ['role' => 'user', 'content' => $v->prompt]);
         $insertGptArr = [['type'=>"text","text"=>$hasPrompt->prompt]];
         array_push($insertGptArr, ['type'=>"image_url","image_url"=>["url"=>$firstImage]]);
         if($type==2){

           array_push($insertGptArr, ['type'=>"image_url","image_url"=>["url"=>$secondImgSrc]]);
         }

         array_push($messages, ['role' => 'user', 'content' => $insertGptArr]);
      }

      $titleContent = [
             'model' => $model,
             'messages' => $messages,
             'temperature'=>"0.7",
             'max_tokens'=>4096,
      ]; 

      
     
      $titleResult = $this->curl($titleContent);
      $titleResult = json_decode($titleResult,true);
      $insertArr = [];


      if(isset($titleResult['choices'])){
          $content = $titleResult['choices'][0]['message']['content'];

          $content = $this->extractJson($content);
          
          $contentArr = json_decode($content,true);
           foreach($list as $k=>$v){


           if($k==0){
              array_push($insertArr,['content'=>$contentArr['zys']."\n".$contentArr['zjb'],'style_id'=>$v->id]);
           }else{

              array_push($insertArr,['content'=>$contentArr['gxb'],'style_id'=>$v->id]);
           }
           
           
        }
      }else{

          fail("解析出错~");
      }
      

     
     
      $record =  $user->picRecords()->create([
            "first_image" =>$firstImage,
            "second_image"=> $secondImgSrc,
            "type"=>$type,
            
       ]);
      if($record){

        foreach($insertArr as $k=>$v){

          $insertArr[$k]['pic_record_id']=$record->id;
        }

        PicContentRecord::insert($insertArr);
      }

      if($type==1){

        $user->decrement("pic_times");
      }else{
         $user->decrement("pic_merge_times");
      }

      $returnRes = [
          "record_id"=>$record->id,
      ];
     
      return response()->json($returnRes);
    }

    public function curl($data){

      $curl = curl_init();
      $data = json_encode($data);


      curl_setopt_array($curl, array(
         CURLOPT_URL => 'https://api.chatanywhere.tech/v1/chat/completions',
         CURLOPT_RETURNTRANSFER => true,
         CURLOPT_ENCODING => '',
         CURLOPT_MAXREDIRS => 10,
         CURLOPT_TIMEOUT => 0,
         CURLOPT_FOLLOWLOCATION => true,
         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
         CURLOPT_CUSTOMREQUEST => 'POST',
         CURLOPT_POSTFIELDS =>$data,
         CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer '.env('CHATGPT_API_KEY'),
            'User-Agent: Apifox/1.0.0 (https://apifox.com)',
            'Content-Type: application/json'
         ),
      ));

      $response = curl_exec($curl);

      
      return $response;
   }


   public function deeppic()
    {
      $id= request('record_id');
      $record = PicRecord::find($id);
     
      return new  UserDivinationRecordPicItemResource($record);
   }

   public function chatRecords()
   {
      $user = request()->user();
      $records = DB::table('sbcs_records as t1')
      ->whereRaw('(
          SELECT COUNT(*) 
          FROM sbcs_records as t2 
          WHERE t2.session_id = t1.session_id 
          AND t2.id <= t1.id
      ) = 2')
      ->where("t1.user_id",$user->id)
      ->orderByDesc("t1.id")->paginate();

      return ChatRecordsResource::collection($records);
   }

   public function chatRecord()
   {
      $user = request()->user();
      $sessionId = request("session_id");
      if(!$sessionId){
        fail("参数不存在!");
      }
      $records = $user->sbcsRecords()->where("session_id",$sessionId)->orderby('id')->get()->slice(1);

      return ChatRecordsResource::collection($records);
   }


   public function chat()
    {

      $user = request()->user();

      $messages= request('messages');
      $sessionId= request('sessionId');

      $cacheKey = 'chatgpt_response_'.md5(json_encode($messages));

      if (Cache::has($cacheKey)) {
          
           $text =  Cache::get($cacheKey);
          
         
      }else{
         $model="qwen3-max";

          array_unshift($messages, ['role' => 'system', 'content' => cs()->prompt]);
          
          $lastMsg = end($messages)['content'];

          //var_dump($lastMsg);
          $reg = '/^(\d+).*?(\d+).*?(\d+)$/ ';
          preg_match($reg, $lastMsg, $matches);
          
          $needReplace = 0;
          if(isset($matches[1]) && isset($matches[2]) && isset($matches[3])){
             $upper_num_remainder = intval($matches[1]) % 8;
             $upper_num_remainder = $upper_num_remainder == 0 ? 8 : $upper_num_remainder;
             $lower_num_remainder = intval($matches[2]) % 8;
             $lower_num_remainder =  $lower_num_remainder == 0 ? 8 : $lower_num_remainder;
             $yao_num_remainder = intval($matches[3]) % 6;
             $yao_num_remainder = $yao_num_remainder == 0 ? 6 : $yao_num_remainder;
             $needReplace = 1;

             $lastMsg = str_replace($matches[1],$upper_num_remainder,$lastMsg);
             $lastMsg = str_replace($matches[2],$lower_num_remainder,$lastMsg);
             $lastMsg = str_replace($matches[3],$yao_num_remainder,$lastMsg);
             
          }

          $aiMessages = $messages;
          $length = count($aiMessages);
          if($needReplace==1){
            $aiMessages[$length-1]['content'] = $lastMsg;

          }

          

          $titleContent = [
                 'model' => $model,
                 'messages' => $aiMessages,
                 'temperature'=>0.7,
                 'max_tokens'=>4096,
          ]; 
         
          $titleResult = $this->qianwenCurl($titleContent);
          $titleResult = json_decode($titleResult,true);
          
          $text = $titleResult['choices'][0]['message']['content'];

          $insertArr = [];
          foreach ($messages as $k=>$message) {
            $insertArr[$k]['user_id'] = $user->id;
            $insertArr[$k]['session_id'] = $sessionId;
            $insertArr[$k]['content'] = $message['content'];
            $insertArr[$k]['created_at'] = date("Y-m-d H:i:s",time());

          }

          array_push($insertArr,["user_id"=>$user->id,'session_id'=>$sessionId,'content'=>$text,'created_at'=>date("Y-m-d H:i:s",time())]);

          SbcsRecord::query()->where("user_id",$user->id)->where("session_id",$sessionId)->delete();
          SbcsRecord::insert($insertArr);



          Cache::put($cacheKey, $text, Carbon::now()->addHours(1));
       
      }

      
     

      return new StreamedResponse(function () use($text) {

        $chunks = $this->splitByFiveChars($text); // 每5字符分块
          
            //var_dump($chunks);
            foreach ($chunks as $chunk) {
                echo "data: " . json_encode(['content' => $chunk,'finished' => false]) . "\n\n";
                ob_flush();
                flush();
                usleep(100000); // 模拟延迟（0.2秒）
            }

            echo "data: " . json_encode(['finished' => true]) . "\n\n";
            ob_flush();
            flush();
        }, 200, [
            'Content-Type' => 'text/event-stream',
            'Cache-Control' => 'no-cache',
            'Connection' => 'keep-alive',
            'X-Accel-Buffering'=> 'no'
        ]);
     
      //return ['msg'=>$titleResult['choices'][0]['message']['content'],'code'=>200];
   }

   public function splitByFiveChars($input) {
      $result = [];
      $length = mb_strlen($input, 'UTF-8');
      
      for ($i = 0; $i < $length; $i += 3) {
          $segment = mb_substr($input, $i, 3, 'UTF-8');
          array_push($result, $segment);
      }
      
      return $result;
  }

  public function qianwenCurl($data){

      $curl = curl_init();
      $data = json_encode($data);


      curl_setopt_array($curl, array(
         CURLOPT_URL => 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
         CURLOPT_RETURNTRANSFER => true,
         CURLOPT_ENCODING => '',
         CURLOPT_MAXREDIRS => 10,
         CURLOPT_TIMEOUT => 0,
         CURLOPT_FOLLOWLOCATION => true,
         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
         CURLOPT_CUSTOMREQUEST => 'POST',
         CURLOPT_POSTFIELDS =>$data,
         CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer '.env('QIANWEN_API_KEY'),
            'User-Agent: Apifox/1.0.0 (https://apifox.com)',
            'Content-Type: application/json'
         ),
      ));

      $response = curl_exec($curl);

      
      return $response;
   }


    public function zzxj()
    { 


      $str = request('str');
      $type = request('type');

      $request = app(DivinationZzxjRequest::class);

      $firstWord = mb_substr($str, 0, 1, "UTF-8");
      $secondWord =mb_substr($str, 1, 1, "UTF-8");

      $upperNumData =HanziRecord::query()->where("name",$firstWord)->first();
      $lowerNumData =HanziRecord::query()->where("name",$secondWord)->first();

      if(!$upperNumData || !$lowerNumData){

         fail("请输入两个汉字！！！");
      }else{
        $upper_num = $upperNumData->num;

        $lower_num = $lowerNumData->num;

        $yao_num = $upper_num+$lower_num;
      }

      
      $user = request()->user();
        
      $upper_num_remainder = intval($upper_num) % 8;
      $upper_num_remainder = $upper_num_remainder == 0 ? 8 : $upper_num_remainder;
      $lower_num_remainder = intval($lower_num) % 8;
      $lower_num_remainder =  $lower_num_remainder == 0 ? 8 : $lower_num_remainder;



     $divination = Divination::query()->where("upper_num",$upper_num_remainder)->where("lower_num",$lower_num_remainder)->first();

     if(!$divination){

        fail("出错了！！！");
     }



      $yao_num_remainder = intval($yao_num) % 6;
      $yao_num_remainder = $yao_num_remainder == 0 ? 6 : $yao_num_remainder;

      $byDivination = YaoDivination::where("yao_count",$yao_num_remainder)->where('divination_id',$divination->id)->first();
      if(!$byDivination){

         fail("出错了！！！");
      }

      $trueByDivination = Divination::find($byDivination->by_dividend_id);
      $text="";

      if($trueByDivination){

         $model="qwen3-max";

         $messages = [];

         $prompt = cs()->zzxj_prompt;
         $prompt = str_replace("{HEXAGRAM_NAME}",$divination->title,$prompt);
         $prompt = str_replace("{TRANSFORMED_HEX_NAME}",$trueByDivination->title,$prompt);
         $prompt = str_replace("{DIRECTION}",$type,$prompt);

         


         array_unshift($messages, ['role' => 'system', 'content' => $prompt]);

          $titleContent = [
               'model' => $model,
               'messages' => $messages,
               'temperature'=>0.7,
               'max_tokens'=>4096,
        ]; 


        
       
        $titleResult = $this->qianwenCurl($titleContent);
        $titleResult = json_decode($titleResult,true);

        $text = $titleResult['choices'][0]['message']['content'];

        $text = str_replace("*","",$text);

        $briefMessage = [];

        $briefModel = "gpt-4o";
        array_unshift($briefMessage, ['role' => 'system', 'content' => '请将下面内容生成一段简单明了的40字的搞笑风格文案']);
        array_unshift($briefMessage, ['role' => 'user', 'content' => $text]);
        $titleContent = [
                 'model' => $briefModel,
                 'messages' => $briefMessage,
                 'temperature'=>0.7,
                 'max_tokens'=>4096,
        ]; 
         
        $titleResult = $this->curl($titleContent);
        $titleResult = json_decode($titleResult,true);
       

        $brief = $titleResult['choices'][0]['message']['content'];
      }



      $arr = [
        'up_name'=>config("site.zzxj")[$upper_num_remainder],
        'down_name'=>config("site.zzxj")[$lower_num_remainder],
        'title'=>$divination->title,
        'bian_title'=>$trueByDivination->title,
        'yao_num'=>$yao_num_remainder,
        'dividend_id'=>$divination->id,
        'by_dividend_id'=>$trueByDivination->id,
        'bengsy'=>$divination->shiyi,
        'bianysy'=>$byDivination->yao_shiyi,
        'tag'=>$byDivination->tag,
        'biangsy'=>$trueByDivination->shiyi,
        'cz'=>$str,
        'type'=>$type,
        'content'=>$text,
        'brief'=>$brief

      ];


    

       $record =  $user->zzxjRecords()->create($arr);

       $arr['record_id'] = $record->id;
       return response()->json($arr);
        
       
       
    }

    public function recordzzxj($id)
    {
      $record = ZzxjRecord::find($id);
      return new  UserDivinationRecordZzxjItemResource($record);
   }
}
